#pragma once
#include "log.hpp"
#include<vector>
#include"inetaddr.hpp"

class Route
{
public:
    Route()
    {

    }

    bool IsExit(const InetAddr& source)
    {
        for(auto it = _online.begin();it < _online.end();++it)
        {
            if(*it  == source)
            {
                return true;
            }
        }
        return false;
    }

    void AddUser(const InetAddr& source)
    {
        _online.emplace_back(source);
        LOG(LogLevel::DEBUG) << "成功增加一个用户,ip:" << source.GetIp() << " 端口号:" << source.GetPort();
    }

    void MessageRoute(int sockfd,const std::string& message,const InetAddr& source)
    {
        std::lock_guard<std::mutex> lg(_mutex);
        if(!IsExit(source))
        {
            AddUser(source);
        }
        std::string sendmess = source.GetIp() + ":" + std::to_string(source.GetPort()) + "# " + message;
        for(auto& e : _online)
        {
            sendto(sockfd,sendmess.c_str(),sendmess.size(),0,(struct sockaddr*)&e.GetAddr(),sizeof(e.GetAddr()));
        }
    }

    ~Route()
    {

    }

private:
    std::vector<InetAddr> _online;
    std::mutex _mutex;
};